// 全局变量
let words = [];
let counter = 0;
let isWordListVisible = false;

// API URL（使用相对路径，这样在部署后也能正常工作）
const API_URL = '/api/words';

// DOM元素
const practiceBtn = document.getElementById('practice-btn');
const randomWord = document.getElementById('random-word');
const counterDisplay = document.getElementById('counter');
const newWordInput = document.getElementById('new-word');
const addWordBtn = document.getElementById('add-word-btn');
const wordListTitle = document.getElementById('word-list-title');
const wordListContent = document.getElementById('word-list-content');

// 从服务器加载词库
async function loadWords() {
    try {
        const response = await fetch(API_URL);
        const data = await response.json();
        words = data.words;
        updateWordList();
    } catch (error) {
        console.error('加载词库失败:', error);
        randomWord.textContent = '加载词库失败，请刷新页面重试';
    }
}

// 保存新词到服务器
async function saveNewWord(newWord) {
    try {
        const response = await fetch(API_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ word: newWord })
        });
        const data = await response.json();
        words = data.words;
        updateWordList();
        return true;
    } catch (error) {
        console.error('保存新词失败:', error);
        randomWord.textContent = '保存失败，请重试';
        return false;
    }
}

// 更新词库显示
function updateWordList() {
    wordListContent.textContent = words.join('、');
}

// 切换词库显示状态
function toggleWordList() {
    isWordListVisible = !isWordListVisible;
    wordListContent.style.display = isWordListVisible ? 'block' : 'none';
    wordListTitle.textContent = isWordListVisible ? '点击隐藏当前词库 ▲' : '点击查看当前词库 ▼';
}

// 生成随机词语
function getRandomWord() {
    const randomIndex = Math.floor(Math.random() * words.length);
    return words[randomIndex];
}

// 更新计数器显示
function updateCounter() {
    counterDisplay.textContent = `已随机次数：${counter}`;
}

// 添加新词汇
async function addNewWord() {
    const newWord = newWordInput.value.trim();
    if (newWord && !words.includes(newWord)) {
        const success = await saveNewWord(newWord);
        if (success) {
            newWordInput.value = '';
            randomWord.textContent = `成功添加新词："${newWord}"`;
        }
    } else if (words.includes(newWord)) {
        randomWord.textContent = '该词已存在于词库中';
    }
}

// 点击按钮事件处理
practiceBtn.addEventListener('click', () => {
    counter++;
    const word = getRandomWord();
    randomWord.textContent = word;
    updateCounter();
});

// 添加词汇按钮事件处理
addWordBtn.addEventListener('click', addNewWord);

// 输入框回车事件处理
newWordInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        addNewWord();
    }
});

// 词库标题点击事件处理
wordListTitle.addEventListener('click', toggleWordList);

// 初始化加载词库
loadWords(); 